package main

import (
	"go-scripts/common"
	"golang.org/x/net/websocket"
	"fmt"
	"runtime/debug"
	"os"
	"log"
	//"bufio"
	//"io"
	//"io/ioutil"
	"encoding/json"
	"go-scripts/models"
	"gopkg.in/mgo.v2/bson"
	"time"
	"bufio"
)

func main()  {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("panic")
			debug.PrintStack()
			log.Fatal(err)
			os.Exit(0)
		}
	}()
	token, err := common.GetToken()
	if err != nil {
		panic(err.Error())
	}
	url := "ws://gw.yundzh.com/ws?token=" + token
	origin := "http://gw.yundzh.com"
	ws, err := websocket.Dial(url, "", origin)
	fmt.Println(url)
	fmt.Println("打开websocket")
	//60秒ping一次，防止断开
	go func(ws *websocket.Conn) {
		for {
			time.Sleep(60 * time.Second)
			ping(ws)
			log.Println("发送ping")
		}
	}(ws)
	if err != nil {
		panic(err.Error())
	}
	common.SubcribeTheme(ws)
	for {
		var res string
		err := websocket.Message.Receive(ws, &res)
		if err != nil {
			fmt.Println("websocket断开")
			os.Exit(0)
		}
		onMessage(res)
	}
}
//处理返回数据
func onMessage(res string)  {
	fmt.Println(res)
	resMap := make(map[string]interface{})
	if err := json.Unmarshal([]byte(res), &resMap); err != nil || resMap["Err"].(float64) != 0 {
		panic(err.Error())
	}
	//qid为0，订阅的则是全部题材
	if resMap["Qid"] == "0" {
		objs := resMap["Data"].(map[string]interface{})["RepDataPaiXu"].([]interface{})
		saveTheme(objs)
	}
}
//保存题材，如果有新题材，则生成主题，否则不生成主题，只更新题材
func saveTheme(objs []interface{})  {
	model := models.GetModel()
	themeDao, err := model.GetModelCollection("Theme")
	effectTopicDao, err := model.GetModelCollection("EffectTopic")
	if err != nil {
		panic(err.Error())
	}
	for _, obj := range objs {
		themeMap := obj.(map[string]interface{})
		theme := new(models.Theme)
		eCode := themeMap["Obj"].(string)
		illegalMap := common.GetIllegalTheme()
		if illegalMap[eCode] != "" {
			continue
		}
		iCode := eCode + ".index"
		name := themeMap["Text"].(string)
		banKuai := "股票/大智慧自定义/指数板块/" + name
		now := time.Now()
		themeDao.Find(bson.M{
			"iCode": iCode,
		}).One(theme)
		if theme.Id_.Hex() == "" {
			err := themeDao.Insert(bson.M{
				"eCode": eCode,
				"iCode": iCode,
				"name": name,
				"banKuai":  banKuai,
				"createdAt": now,
				"updatedAt": now,
			})
			if err != nil {
				panic(err.Error())
			}
			common.CreateThemeTopic(name, iCode, "", effectTopicDao)
		} else {
			themeDao.Update(bson.M{
				"iCode": iCode,
			}, bson.M{
				"$set": bson.M{
					"name": name,
					"banKuai": banKuai,
					"updatedAt": now,
				},
			})
		}
	}
}
//ping
func ping(ws *websocket.Conn)  {
	w := bufio.NewWriter(ws)
	w.Write([]byte("ping"))
	w.Flush()
}